<?php

namespace App\Http\Controllers;

use App\Rule;
use App\User;
use Illuminate\Http\Request;

class RulesController extends Controller
{
    public function __construct() {
        $this->middleware('auth');
    }

    public function getAll() {
        $rule=Rule::all();
        return response()->json($rule);
    }
    public function getCurrent($page) {
        $pages=$page*10-10;
        $rule=Rule::skip($pages)->take(10)->get();
        return response()->json($rule);
    }
    public function getCount() {
        $rule=Rule::all()->count();
        return response()->json($rule);
    }
    public function add($userId,Request $request) {

       Rule::where('uid',$userId)->delete();
       $add['uid']=$userId;
        if ($request->input('rule')){
            $rule=$request->input('rule');
            foreach ($rule as $r){
                $add['name']=$r;
                Rule::create($add);
            }

        }

        return response()->json('添加成功');
    }
    public function del ($id) {
        $rule=Rule::find($id);
        if($rule){
            $rule->delete();
            return response()->json('删除成功');
        }
        return response()->json('用户不存在');

    }
    public function update($id, Request $request) {
        $adduser = Rule::find($id);
        if($request->input('password') !='' ){
            if($request->input('password') === $request->input('password_confirmation') ){
                $adduser->password = Hash::make($request->input('password'));
            }else{
                return response()->json('密码不相同');
                dd();
            }
        }
        $adduser->name = $request->input('name');
        $adduser->save();
        Rule::where('uid',$id)->delete();
        $addr['uid']=$id;
        if ($request->input('rule')){
            $rule=$request->input('rule');
            foreach ($rule as $r){
                $addr['name']=$r;
                Rule::create($addr);
            }
        }
        return response()->json('修改成功');
    }
    public function search($word) {
        $rule=Rule::where('name','like','%'.$word.'%')->OrWhere('email','like','%'.$word.'%')->get();
        return response()->json($rule);
    }
    public function page($page,$pagesize) {
        $skip=$page*$pagesize;
        $take=$pagesize;
        $rule=Rule::orderBy('id','desc')->skip($skip)->take($take)->get();
        return response()->json($rule);
    }
    public function dateOne($date) {

        $rule=Rule::where('created_at',$date)->get();
        return response()->json($rule);
    }
    public function datemore($date) {

        $rule=Rule::where('created_at',$date)->get();
        return response()->json($rule);
    }

    public function one($id) {
        $rule=Rule::find($id);
        return response()->json($rule);
    }

}
